<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\Collect;
use App\Model\MultiCollect;
use App\Model\MultiLearn;
use App\Model\MultiZan;
use App\Model\News;

use App\Model\NewsComment;
use App\Model\NewsJoin;
use App\Model\Notify;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]

class NewsController extends AppBaseController
{

    /**
     * 资讯发布|列表
     * @param int $type
     * @return object
     */
    #[RequestMapping(path:'newsList/{type}',methods: 'get')]
    public function newsList(int $type=0): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;


            $where['status'] = 1;
            $where['is_long'] = 1;

            $dateTime = date('Y-m-d H:i:s',time());
            $whereOr = [
                ['status','=',1],
                ['show_start_at','<=',$dateTime],
                ['show_end_at','>=',$dateTime],
            ];

            $whereIn = [1,2,3,4];
            if(is_numeric($type) && $type!=0){
                if($type==1){
                    $whereIn = [1];
                }else{
                    $whereIn = [2,3,4];
                }
            }

            $list = News::with(['party'=>function($query){
                        $query->selectRaw('id,name')->get();
                    }])->where($where)
                    ->orWhere($whereOr)
                    ->whereIn('type',$whereIn)
                    ->selectRaw('id,party_id,type,title,photo,link_id,link_url,created_at')
                    ->orderByDesc('id')
                    ->offset($offset)
                    ->limit($limit)
                    ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 资讯|详情
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path:'newsInfo/{news_id}',methods: 'get')]
    public function newsInfo(int $news_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];
            
            $info = News::where('id',$news_id)
                ->selectRaw('id,type,title,photo,content,file_list,learn_count,created_at')
                ->first();
            if(empty($info)) return $this->reMsg->re(10008);

            $info->is_collect = 0;
            $info->is_learn = 0;
            $info->is_zan = 0;
            //处理用户是否收藏
            $whereDo['module'] = 'news';
            $whereDo['relation_id'] = $info->id;

            //获取点赞数量
            $info->zan_count = MultiZan::where($whereDo)->count();

            $whereDo['uid'] = $_user->id;
            //判断是否学习
            $learnInfo = MultiLearn::where($whereDo)->first();
            if($learnInfo) $info->is_learn = 1;
            //判断是否收藏
            $whereDo['status'] = 1;
            $collectInfo = MultiCollect::where($whereDo)->first();
            if($collectInfo) $info->is_collect = 1;
            //判断是否点赞
            $zanInfo = MultiZan::where($whereDo)->first();
            if($zanInfo) $info->is_zan = 1;


            //处理用户的资讯模块为已处理
            $whereNotify['module'] = 1;
            $whereNotify['relation_id'] = $info->id;;
            $whereNotify['uid'] = $_user->id;
            $notifyInfo = Notify::where($whereNotify)->first();
            if($notifyInfo && $notifyInfo->status==0){
                $notifyInfo->status = 1;
                $notifyInfo->save();
            }
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 资讯发布|30s任务
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path: 'newsJoin/{news_id}',methods: 'get')]
    public function newsJoin(int $news_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $info = News::where('id',$news_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            $data['party_id'] = $_user->party_id;
            $data['news_id'] = $news_id;
            $data['uid'] = $_user->id;
            $data['type'] = $info->type;
            $joinInfo = NewsJoin::where($data)->first();
            if($joinInfo)  return $this->reMsg->re(10010);
            $insertRet = NewsJoin::create($data);
            if($insertRet){
                //学习人数加1
                News::where('id',$news_id)->increment('learn_count',1);
                //加积分
                $params = [
                    'type'=> 1, //活动答题 type 1:学习 2:评论 5:答题 6:报名 7:抽奖 8:签到 9:问卷
                    'action' => 1, //action 1:加积分 2:减积分
                    'uid' => $_user->id,  //用户id
                    'party_id' => $_user->party_id   //支部id
                ];
                $this->makeIntegralLog($params);
            }
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 资讯发布|完成列表
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path:'newsJoinList/{news_id}',methods: 'get')]
    public function newsJoinList(int $news_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['news_id'] = $news_id;
            $list = NewsJoin::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->get();
                }])
                ->selectRaw('id,uid,created_at')
                ->orderByDesc('id')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 资讯发布|评论
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path: 'newsComment/{news_id}',methods: 'post,get')]
    public function newsComment(int $news_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $info = News::where('id',$news_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);

            $content = $this->request->input('content','这是测试评论');
            if(empty($content)) return $this->reMsg->re(0,'评论信息不可为空');

            $data['party_id'] = $_user->party_id;
            $data['news_id'] = $news_id;
            $data['uid'] = $_user->id;
            $data['content'] = $content;
            $data['type'] = $info->type;
            $insertRet = NewsComment::create($data);
            if($insertRet){
                //评论人数加1
                News::where('id',$news_id)->increment('comment_count',1);

                //评论的积分前提条件式 每天只能评论5次的积分
                //查询今天已经参与了几次
                $day = date('Y-m-d',time());
                $dayStartTime = $day.' 00:00:00';
                $dayEndTime = $day.' 23:59:59';
                $readyCount = NewsComment::where(['uid'=>$_user->id,'news_id'=>$news_id])
                    ->whereBetween('created_at',[$dayStartTime,$dayEndTime])->count();
                if($readyCount<2){
                    //加积分
                    $params = [
                        'type'=> 2, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到 9:问卷 10:支部信息更新
                        'action' => 1, //action 1:加积分 2:减积分
                        'uid' => $_user->id,  //用户id
                        'party_id' => $_user->party_id  //支部id
                    ];
                    $this->makeIntegralLog($params);
                }
                return $this->reMsg->re(1);
            }else{
                return $this->reMsg->re(0);
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




    /**
     * 资讯发布|评论列表
     * @param int $news_id
     * @return object
     */
    #[RequestMapping(path:'newsCommentList/{news_id}',methods: 'get')]
    public function newsCommentList(int $news_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['news_id'] = $news_id;
            $list = NewsComment::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->get();
                }])
                ->selectRaw('id,uid,content,created_at')
                ->orderByDesc('id')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }






}